package com.apes.framework.plugin.mq;

import com.alibaba.fastjson.JSON;
import com.apes.framework.api.SpringManager;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.plugin.event.Listener;
import com.apes.framework.plugin.mq.domain.MQueue;
import com.apes.framework.util.ReflectUtil;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * 功能：MQ相关工具类
 *
 * @author xul
 * @create 2018-02-02 13:41
 */
@Service
public class MQUtil {

    public static void publish(String topic, String description, Object body) {
        if (body == null) return;
        MQueue message = new MQueue();
        message.setTopic(topic);
        message.setDescription(description);
        if (ReflectUtil.isPrimitive(body.getClass())) {
            message.setBody(String.valueOf(body));
        } else {
            message.setBody(JSON.toJSONString(body));
        }
        publish(message);
    }

    public static void publish(MQueue message) {
        Channel channel = SpringManager.getBean(MessageChannel.class);
        channel.publish(message);
    }

    @Listener(topic="event:mq.publish")
    public void publish(SimpleRequest request){
        Map data = request.getMap();
        publish((String) data.get("topic"), (String) data.get("description"), data.get("body"));
    }
}
